// 导入表单验证插件
import wxValidate from 'wechat-validate'

Page({
  data: {
    countDownVisible: false,
    //手机号
    mobile: '',
    code: ''
  },
  //通过behaviors注入validate方法
  behaviors: [wxValidate],//this上面就会有validate方法
  //校验规则
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' }
    ],
    code: [
      { required: true, message: '请填写短信验证码!' },
      { pattern: /^\d{6}$/, message: '请检查短信验证码是否正确!' }
    ]
  },
  onLoad(options) {
    // console.log(options)
    this.redirectUrl = options.redirectUrl
  },
  //获取验证码
  async getSMSCode() {
    //校验手机号是否正确
    const res = this.validate('mobile')
    // console.log(res);
    const { message, valid } = res
    if (!valid) return wx.utils.toast(message)
    //显示倒计时
    this.setData({ countDownVisible: true })
    //发起请求
    const { code } = await wx.http.get('/code', { mobile: this.data.mobile })
    this.setData({
      code
    })
  },
  //监听倒计时组件数值的变化
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 登录提交
  async login() {
    //表单完整校验
    let valid = this.validate() //校验rules定义好的字段
    //自动校验所有字段，哪个字段没有通过，会自动弹框提示，返回校验结果是布尔值
    if (!valid) return
    //发送请求
    const res = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.code
    })
    // console.log(res)
    //提示成功
    wx.utils.toast('bingo~honey!', 'success')
    // 存储token
    let app = getApp()
    app.setToken('token', res.token)
    app.setToken('refreshToken', res.refreshToken)
    //跳转页面
    wx.redirectTo({
      url: '/' + this.redirectUrl
    })
  }
})
